//
//  Util.m
//  OrderApp1
//
//  Created by trimad on 11-11-6.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Util.h"

#import "JSON.h"

#import "Item.h"
#import "Order.h"
#import "OrderItem.h"

@implementation Util

+ (NSString *)getParentFolder {
	return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}

+ (NSString *)getPath:(NSString *)name {
	return [[self getParentFolder] stringByAppendingPathComponent:name];
}

+ (NSString *)readResourceForString:(NSString *)name {
	return [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:nil] encoding:NSUTF8StringEncoding error:nil];
}

+ (UIImage *)readResourceForImage:(NSString *)name {
	return [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:nil]];
}

+ (NSString *)readFileForString: (NSString *) name {
	return [[NSString alloc] initWithContentsOfFile:[self getPath:name] encoding:NSUTF8StringEncoding error:nil];
}

+ (void)writeFileForString:(NSString *)aString: (NSString *) name {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	[fileManager changeCurrentDirectoryPath:[[self getParentFolder] stringByExpandingTildeInPath]];
	[fileManager removeItemAtPath:name error:nil];
	[aString writeToFile:[self getPath:name] atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

+ (NSMutableDictionary *)readFileForDictionary: (NSString *) name {
	return [[NSMutableDictionary alloc] initWithContentsOfFile:[self getPath:name]];;
}

+ (void)writeFileForDictionary:(NSMutableDictionary *)dictionary: (NSString *) name {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	[fileManager changeCurrentDirectoryPath:[[self getParentFolder] stringByExpandingTildeInPath]];
	[fileManager removeItemAtPath:name error:nil];
	[dictionary writeToFile:[self getPath:name] atomically:YES];
}

+ (UIImage *)readFileForImage: (NSString *) name {
	return [[UIImage alloc] initWithContentsOfFile:[self getPath:name]];
}

+ (void)writeFileForImage:(UIImage *)image: (NSString *) name {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	[fileManager changeCurrentDirectoryPath:[[self getParentFolder] stringByExpandingTildeInPath]];
	[fileManager removeItemAtPath:name error:nil];
	[UIImagePNGRepresentation(image) writeToFile:[self getPath:name] atomically:YES];
}

+ (NSString *)getServiceHost {
	//NSLog(@"getServiceHost");
	NSString* hostString=[[NSString alloc] initWithString:@"http://192.168.1.102:8080/"];
	return hostString;
}

+ (NSString *)getResponseByURL: (NSString *) urlString {
	//NSLog(@"getResponseByURL");
	NSURL *url = [NSURL URLWithString:urlString];
	NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
	NSData *response = [NSURLConnection sendSynchronousRequest:requestObj returningResponse: nil error: nil];
	NSString * aResponse = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
	return aResponse;
}

+ (NSString *)getOrderJsonDataFromService {
	//NSLog(@"getCategoryItemsJsonDataFromService");
	NSString* tempStr=[self readFileForString:@"localOrderJsonData"];
	NSLog(@"11 %@",tempStr);
	if(tempStr != nil){
		return tempStr;
	}else {
		NSString* urlString=[[self getServiceHost] stringByAppendingString:[[NSString alloc] initWithString:@"getOrder.jsp"]];
		tempStr=[self getResponseByURL:urlString];
		[self writeFileForString:tempStr :@"localOrderJsonData"];
		return tempStr;
	}
}

+ (Order *)getOrderFromService {
	//NSLog(@"getOrderFromService");
	Order *order=[[Order alloc] init];
	NSString* tempStr=[self getOrderJsonDataFromService];
	NSDictionary *formatString=(NSDictionary *)[(NSArray *)[tempStr JSONValue] objectAtIndex:0];
	
	order.note=[formatString objectForKey:@"notes"];
	NSMutableArray *tempArray=[[NSMutableArray alloc] init];
	NSArray *orderItems=[formatString objectForKey:@"items"];
	for(id orderItem in orderItems){
		NSDictionary *tempDic1=(NSDictionary *)orderItem;
		OrderItem *tempOrderItem=[[OrderItem alloc] init];
		Item *tempItem=[[Item alloc] init];
		tempItem.code=[tempDic1 objectForKey:@"code"];
		tempOrderItem.item=tempItem;
		tempOrderItem.quantity=[[tempDic1 objectForKey:@"quantity"] intValue];
		tempOrderItem.note=[tempDic1 objectForKey:@"notes"];
		
		[tempArray addObject:tempOrderItem]; 
	}
	order.orderItems=tempArray;
	//NSLog(@"order: %@",order);
	
	return order;
}

+ (void)saveOrderFromService: (Order *) order {
	//NSLog(@"saveOrderFromService");
	NSString* urlString=[[self getServiceHost] stringByAppendingString:[[NSString alloc] initWithString:@"SaveOrder"]];
	NSString *temp=@"order={notes:";
	temp=[temp stringByAppendingString:order.note];;
	temp=[temp stringByAppendingString:@",items:"];
	NSArray *orderItems=order.orderItems;
	int count=1;
	for(id tempOrderItem in orderItems){
		OrderItem *tempOI=(OrderItem *) tempOrderItem;
		temp=[temp stringByAppendingFormat:@"{code:%@",tempOI.item.code];
		temp=[temp stringByAppendingFormat:@",notes:%@",tempOI.note];
		temp=[temp stringByAppendingFormat:@",quantity:%i}",tempOI.quantity];
		
		if(count != [orderItems count]){
			temp=[temp stringByAppendingString:@","];
		}
		count++;
	}
	temp=[temp stringByAppendingString:@"}"];
	NSMutableURLRequest *request=[NSMutableURLRequest new];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	NSData *postBody=[temp dataUsingEncoding:NSUTF8StringEncoding];
	[request setHTTPBody:postBody];
	NSData *data=[NSURLConnection sendSynchronousRequest:request
									   returningResponse:nil error:nil];
	NSString *strRet=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	//NSLog(@"strRet: %@", strRet);
	[strRet release];
}

@end
